package org.zsl.controller.springmvc;


import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.zsl.model.ResponseMsg;

import javax.servlet.ServletContext;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

@RestController
@RequestMapping("/file")
public class FileController {

    @RequestMapping("/upload")
    public ResponseMsg upload(MultipartFile photo, HttpSession session) throws IOException {

        /**
         *  step1: 获取源文件信息
         * */

        String fileName = photo.getOriginalFilename();
        System.out.println("1.filename:" + fileName);
        String hzname = fileName.substring(fileName.lastIndexOf("."));
        System.out.println("2.hzname:" + hzname);
        fileName = "test001" + hzname;


        /**
         *  step2；创建保存目录
         * */

        ServletContext context = session.getServletContext();
        String realPath = context.getRealPath("upload");
        System.out.println("3.realPath:" + realPath);

        File file = new File(realPath);
        if (!file.exists()) {
            file.mkdir();
        }


        /**
         *  3. 把浏览器传递过来的文件
         *  保存在服务器所在的物理硬盘上
         * */

        String finalPath = realPath + File.separator + fileName;

        System.out.println("4.finalPath：" + finalPath);

        photo.transferTo(new File(finalPath));

        return new ResponseMsg();

    }


    @RequestMapping("/download/{filename}")
    public void download(@PathVariable("filename") String filename
            , HttpServletRequest request
            , HttpServletResponse response) throws IOException {


        /**
         * 1. 创建关联本地文件的文件输入流
         * */

       String realPath= request.getSession().getServletContext().getRealPath("upload");

       filename = filename+"."+"jpg";

       File file = new File(realPath,filename);

        FileInputStream fileInputStream = new FileInputStream(file);

        /**
         *  2. 设置response
         * */

        response.setContentType("text/plain;charset=UTF-8");
        response.setHeader("content-disposition","attachment;fileName="+filename);

        /**
         * 3.获取输出流 并完成本地文件构建
         * */

        ServletOutputStream os = response.getOutputStream();


        int len;
        byte[] bytes = new  byte[1024];

        while (true){

            len = fileInputStream.read(bytes);

            if(len==-1) break;
            os.write(bytes,0,len);
        }


        os.close();
        fileInputStream.close();
    }
}
